<template>
	<view class="load" v-if="!load">
		<u-loading-icon mode="circle" inactive-color="#fff" text="正在加载..." vertical></u-loading-icon>
	</view>
	<block v-else>
		<image class="bgImg" src="https://giftapp.oss-cn-shenzhen.aliyuncs.com/upload/17217247864561204.png" mode="">
		</image>
		<view class="container">
			<view class="navBox" :class="isNav?'white':''">
				<topStatus></topStatus>
				<view class="tabsBack">
					<view @click="goBack()" class="blackbox">
						<uni-icons type="left" size="30"></uni-icons>
					</view>
					<view class="topTitle hiddenText" v-show="topNav"></view>
				</view>
			</view>
			
			<view class="giverName">
				<view class="giverFont">{{ user.SenderName }}</view>
			</view>
			<view class="titleImg">
				<image src="https://giftapp.oss-cn-shenzhen.aliyuncs.com/upload/172178829989152.png" mode="widthFix">
				</image>
			</view>

			<view class="canvas">
				<!-- <view class="canvas_head">
					<view class="canvas_avatar">
						<image src="https://giftapp.oss-cn-shenzhen.aliyuncs.com/upload/17217271966401435.jpg"
							mode="widthFix"></image>
					</view>
					张筱雨送了您一份心意
				</view> -->
				<view class="canvas_cover">
					<image :src="user.img" mode="aspectFill"></image>
				</view>
				<view class="product_name" @click="$refs.beReceived.open()">
					{{ user.ProductName }}
				</view>
				<view class="product_specs">
					<view class="product_spec">
						{{ user.ProductStyle }}｜{{ user.Qty }}份
					</view>
					<view class="product_info" @click="nav_to(`/pages/shop/detail?id=${user.ProductID}`)">
						查看商品详情
					</view>
				</view>

				<block v-if='addressInfo'>
					<view class="product_tip">
						<text>礼物正在快马加鞭地赶来～</text>
					</view>
					<view class="recipient">
						<view class="recipient_head">
							<view class="left">
								<view class="name">
									{{ addressInfo.Accepter }}
								</view>
								<view class="number">
									{{ addressInfo.Phone }}
								</view>
							</view>
							<view class="edit" @click.stop="setAddress(1)">
								修改
							</view>
						</view>
						<view class="address">
							{{addressTotal}}{{ addressInfo.Address }}
						</view>
					</view>

					<view class="product_btn">
						<view @click="nav_to('/pages/tab/home')">
							查看更多好礼
						</view>
					</view>
				</block>

				<block v-else>
					<view class="product_tip">
						礼物已在路上，请填写地址吧
					</view>

					<view class="product_btn">
						<view @click.stop="setAddress(2)">
							请填写地址
						</view>
					</view>
				</block>

				<view class="addAddress" style="display: none;">
					您还没有收货地址，<span>添加收货地址</span>
				</view>
			</view>
		</view>

		<uni-popup ref="setInformation" type="center">
			<view class="setAddress">
				<view class="popupItems">
					<view class="popupTitle">
						填写收货信息
						<image src="https://giftapp.oss-cn-shenzhen.aliyuncs.com/upload/1722311090499840.png"
							@click="$refs.setInformation.close();"></image>
					</view>
					<view class="item">
						<view class="item_title">
							收货人
						</view>
						<view class="item_content">
							<input type="text" v-model="receiverName" placeholder="请输入收货人" />
						</view>
					</view>
					<view class="item">
						<view class="item_title">
							联系电话
						</view>
						<view class="item_content">
							<input type="tel" v-model="receiverPhone" placeholder="请输入联系电话" />
						</view>
					</view>
					<view class="item">
						<view class="item_title">
							所在地区
						</view>
						<view class="item_content" @click="showCity = true">
							<picker mode="region" :value="region" @change="chooseAddressTotal">
								<view class="picker" :style="{color:addressTotal=='请选择所在地区'?'#b9b9b9':'#141414'}">
									{{addressTotal}}
								</view>
							</picker>
						</view>
					</view>
					<view class="item">
						<view class="item_title">
							详细地址
						</view>

						<textarea v-model="receiverAddress" placeholder="请输入详细地址"></textarea>
					</view>
				</view>

				<view class="saveAddress" @click="submit">
					确认保存
				</view>
			</view>
		</uni-popup>
	
		<uni-popup ref="beReceived" type="center">
			<view class="closeReceived">
				<image src="https://giftapp.oss-cn-shenzhen.aliyuncs.com/upload/1722583211485732.png" mode="" @click="$refs.beReceived.close()"></image>
			</view>
			<view class="receivedAll">
				<view class="receivedImg">
					<image src="https://giftapp.oss-cn-shenzhen.aliyuncs.com/upload/1722583051948705.png" mode="aspectFill"></image>
				</view>
				<view class="receivedTitle">
					心意被领完啦～
				</view>
				<view class="receivedTip">
					去看看其他的助农产品吧
				</view>
				<view class="receivedBtn" @click="nav_to('/pages/tab/home')">
					去首页逛逛
				</view>
			</view>
		</uni-popup>
	
	</block>
</template>

<script>
	export default {
		data() {
			return {
				load: false,
				key: '',
				user: {},
				addressInfo: {},
				receiverName: '',
				receiverPhone: '',
				receiverAddress: '',
				showCity: true,
				region:[],
				subType: 0,
				isNav:false,
				isOne:0
			};
		},

		computed: {
			addressTotal(){
				let list = this.region;
				if (list[0] == list[1]) {
					list.splice(0,1)
				}
				return list.join('') || '请选择所在地区';
			},
		},

		watch: {

		},

		onReady() {

		},
		async onLoad(e) {
			this.key = e.ABC;
			console.log('keyyyyyyyyyyyyyyy值',this.key);
			this.fetchData(this.key);
			// OK来到这个页面，要先用key获取商品信息，判断这个商品是否被领取过（是否还有库存）
			// // 先判断礼品是否被领取，如果已被领取过判断还有没有库存，如果未被领取判断有没有地址
			// 判断礼品是否被领取，如果已被领取直接结束，如果未被领取判断有没有库存
			// 判断有没有库存，如果没有库存就弹窗说库存不足，如果有判断地址
			// 判断有没有地址，有的话直接调用领取接口
			// 填完地址点提交回到第一步重新判断
		},
		async onShow() {


		},
		onPageScroll(e) {
			this.isNav = e.scrollTop > 5 ? true : false
		},
		onUnload() {

		},
		methods: {
			// 获取商品信息
			async fetchData(key) {
				const res = await this.$api.post('/SendGift/Detail', {
					BatchNo: key
				});
				console.log('res===============接口==============',res);
				if (res.code == 0) {
					this.user = res.data
					if(this.user.Images){
						this.user.img = this.user.Images.split(',')[0];
					}
				
					// setTimeout(() => {
					// 	// 判断本人是否领取过，
					// 	if() {
					// 		// 如果已领取
					// 		this.$pv.msg('您已领取赠送')
					// 		return
					// 	} else {
					// 		// 未领取，判断库存是否足够
					// 		if() {
					// 			// 打开库存不足弹窗
					// 			return
					// 		}
							
							this.getAddress();
					// 	}
					// }, 1200);
				}else{
					this.$pv.msg(res.message)
					this.$refs.beReceived.open()
				}
			},

			// 查看有无收货地址
			async getAddress() {
				let res = await this.$api.post('/UserAddress/MyDefaultAddress');
				console.log('地址接口========',res);
				if(res.code==109 && this.isOne==0){
					this.isOne = 1
					setTimeout(()=>{
						this.getAddress()
					},500)
					
					return
				}
				if (res.code == 0) {
					this.addressInfo = res.data
					console.log('获取地址==================');
					if (res.data) {
						// 有的话调用创建订单接口
						console.log('有地址==================');
						let obj = {
							ProductID: this.user.ProductID,
							Price: 0,
							Qty: this.user.Qty,
							Style: this.user.ProductStyle,
						}
						let params = {
							Delivery_Accepter: this.addressInfo.Accepter, // 收件人
							Delivery_Phone: this.addressInfo.Phone, // 收件人电话
							Remark: '', // 订单备注
							ItemStr: JSON.stringify([obj]), // 订单明细 Json字符串
							Delivery_Province: this.addressInfo.Province,
							Delivery_City: this.addressInfo.City,
							Delivery_Address: this.addressInfo.Address, // 快递地址（全地址）
							ShopID: this.user.ShopID, // 商户ID
							SendBatchNo: this.key
						}
						console.log('创建订单==================');
						console.log('-----------',JSON.stringify(params));
						const response = await this.$api.post('/SendGift/WXAccept', params);
						console.log('创建订单信息=========',response);
						if(response.code == 0) {
							this.$pv.msg('领取成功')
						} else if(response.code == 100) { // 好像到这里不会有已领取的情况了。。。我也不知道
							this.$pv.msg(response.message)
						} else {
							this.$pv.msg('领取失败')
						}
						

						// 定义回显
						this.receiverName = this.addressInfo.Accepter;
						this.receiverPhone = this.addressInfo.Phone;
						this.region = [this.addressInfo.Province, this.addressInfo.City, this.addressInfo.Area];
						this.receiverAddress = this.addressInfo.Address;
					}
					this.load = true;
				}
			},

			// 打开地址弹窗
			setAddress(index) {
				this.subType = index
				this.$refs.setInformation.open()
			},

			// 保存收货信息
			async submit() {
				if (this.receiverName == '') {
					this.$pv.msg("请输入收货人姓名")
					return
				}
				if (this.receiverPhone == '') {
					this.$pv.msg("请输入收货人电话")
					return
				}
				if (this.region == 0) {
					this.$pv.msg("请选择所在地区")
					return
				}
				if (this.receiverAddress == '') {
					this.$pv.msg("请输入详细地址")
					return
				}
				// 这里判断是添加地址还是修改地址，调用的接口不同
				if(this.subType = 2) {
					await this.AddAddress()
				} else {
					await this.EditAddress()
				}
				// 重新调用地址接口,里面调领取接口
				this.getAddress()
				// 关闭弹窗
				this.$refs.setInformation.close()
				
			},
			//修改地址
			async EditAddress(){
				const res = await this.$api.post('/UserAddress/Edit', {
					Province: this.region[0],
					City: this.region[1],
					Area: this.region[2],
					Address: this.receiverAddress,
					Accepter: this.receiverName,
					Phone: this.receiverPhone, 
					IsDefault: 1,
					ID: this.addressInfo.ID
				});
				if(res.code==0){
					this.$pv.msg('修改完成')
				}else{
					this.$pv.msg(res.message)
				}
			},
			//添加地址
			async AddAddress(){
				const res = await this.$api.post('/UserAddress/Add', {
					Province: this.region[0],
					City: this.region[1],
					Area: this.region[2],
					Address: this.receiverAddress,
					Accepter: this.receiverName,
					Phone: this.receiverPhone, 
					IsDefault: 1
				});
				if(res.code==0){
					this.$pv.msg('添加完成')
				}else{
					this.$pv.msg(res.message)
				}
			},

			// 选择地区
			chooseAddressTotal(e) {
				console.log('picker发送选择改变，携带值为', e)
				this.region = e.detail.value;
			},

			//返回上一页
			goBack() {
				const pages = getCurrentPages();
				if (pages.length > 1) {
					// 如果页面栈长度大于1，则说明有上一页，可以返回
					uni.navigateBack();
				} else {
					// 如果没有上一页，则导航到首页
					uni.reLaunch({
						url: '/pages/tab/home'
					});
				}
			},
		},
	};
</script>

<style lang="scss">
	.bgImg {
		position: fixed;
		width: 100vw;
		height: 100vh;
		top: 0;
		left: 0;
		z-index: -1;
	}

	page {
		// height: 100%;
		// background: url('https://giftapp.oss-cn-shenzhen.aliyuncs.com/upload/17217247864561204.png');
		background-size: 100% 100%;
	}

	.container {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 80rpx 0;
		.white{
			background-color: #FFFFFF;
		}
			.navBox{
				position: fixed;
				width: 100%;
				box-sizing: border-box;
				top: 0;
				left: 0;
				z-index: 999;
				.tabsBack {
					height: 44px;
					display: flex;
					align-items: center;
					padding-left: 16rpx;
					.blackbox {
						width: 52rpx;
						height: 52rpx;
						display: flex;
						align-items: center;
					}
				}
			}
		

		.giverName {
			text-align: left;
			width: 646rpx;
			margin-top: 80rpx;

			.giverFont {
				font-weight: bold;
				font-size: 48rpx;
				color: #F9F7DB;
			}
		}

		.titleImg {
			width: 646rpx;
			height: 80rpx;
			margin: 20rpx 0 40rpx 0;

			image {
				width: 100%;
			}
		}

		.canvas {
			width: 646rpx;
			background: #FFFFFF;
			border-radius: 24rpx;
			padding: 40rpx 40rpx 0 40rpx;

			.canvas_head {
				display: flex;
				align-items: center;
				font-size: 28rpx;
				color: #333333;
				margin-bottom: 25rpx;

				.canvas_avatar {
					width: 72rpx;
					height: 72rpx;
					border-radius: 36rpx;
					overflow: hidden;
					margin-right: 17rpx;

					image {
						width: 100%;
					}
				}
			}

			.canvas_cover {
				width: 566rpx;
				height: 566rpx;
				border-radius: 8rpx;
				overflow: hidden;

				image {
					width: 100%;
					height: 100%;
				}
			}

			.product_name {
				font-weight: bold;
				font-size: 32rpx;
				color: #333333;
				margin: 25rpx 0;
			}

			.product_specs {
				display: flex;
				justify-content: space-between;
				margin: 10rpx 0;

				.product_spec {
					font-size: 28rpx;
					color: #F91C1C;
					font-weight: bold;
				}

				.product_info {
					font-size: 24rpx;
					color: #999999
				}
			}

			.product_tip {
				margin: 40rpx 0;
				font-size: 28rpx;
				color: #333333;
				display: flex;
				align-items: center;
				justify-content: center;

				text {
					width: 100%;
					margin-top: -15rpx;
				}
			}

			.product_btn {
				display: flex;
				align-items: center;
				justify-content: center;
				margin: 40rpx 0;

				view {
					width: 520rpx;
					height: 88rpx;
					background: linear-gradient(270deg, #FD0639 0%, #FE6956 100%);
					border-radius: 48rpx;
					font-weight: bold;
					font-size: 32rpx;
					color: #FFFFFF;
					display: flex;
					align-items: center;
					justify-content: center;
				}
			}



			.recipient {
				margin-bottom: 40rpx;
				width: 598rpx;
				background: #F6F6F6;
				border-radius: 8rpx;
				padding: 25rpx;
				margin-left: -16rpx;

				.recipient_head {
					display: flex;
					align-items: center;
					justify-content: space-between;

					.left {
						font-size: 28rpx;
						color: #333333;
						display: flex;

						.name {}

						.number {
							margin-left: 15rpx;
						}
					}

					.edit {
						font-size: 24rpx;
						color: #5d8bf8;
					}
				}

				.address {
					font-size: 24rpx;
					color: #666666;
					margin-top: 15rpx;
				}
			}
		}

		.addAddress {
			margin-bottom: 60rpx;
			font-size: 28rpx;
			color: #333333;
			display: flex;
			align-items: center;
			justify-content: center;

			span {
				color: #5d8bf8;
			}
		}

	}

	.setAddress {
		width: 670rpx;
		height: 810rpx;
		background: #FFFFFF;
		border-radius: 24rpx;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		align-items: center;
		padding: 40rpx 40rpx 50rpx 40rpx;

		.popupItems {
			display: flex;
			flex-direction: column;
			align-items: center;
			width: 100%;

			.popupTitle {
				font-weight: bold;
				font-size: 36rpx;
				color: #333333;
				margin-bottom: 30rpx;

				image {
					width: 40rpx;
					height: 40rpx;
					position: absolute;
					right: 40rpx;
				}
			}

			.item {
				display: flex;
				width: 100%;
				margin: 15rpx 0;
				height: 80rpx;
				align-items: center;
				justify-content: space-between;

				.item_title {
					font-weight: bold;
					font-size: 28rpx;
					color: #333333;
				}

				.item_content {
					width: 460rpx;
					height: 80rpx;
					background: #F5F5F5;
					border-radius: 8rpx;
					display: flex;
					align-items: center;
					padding-left: 25rpx;

					input {
						font-size: 28rpx;
						color: #000;
					}
				}

				textarea {
					width: 460rpx;
					height: 120rpx;
					background: #F5F5F5;
					margin-top: 45rpx;
					padding: 20rpx 20rpx 10rpx 20rpx;
					font-size: 28rpx;
					color: #000;
					box-sizing: border-box;
				}

			}
		}

		.saveAddress {
			width: 574rpx;
			height: 88rpx;
			background: linear-gradient(270deg, #FD0639 0%, #FE6956 100%);
			border-radius: 44rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			font-weight: bold;
			font-size: 32rpx;
			color: #FFFFFF;
		}
	}

	.closeReceived {
		display: flex;
		justify-content: flex-end;
		padding-bottom: 35rpx;
		
		image {
			width: 60rpx;
			height: 60rpx;
		}
	}

	.receivedAll {
		width: 630rpx;
		height: 708rpx;
		background: #FFFFFF;
		border-radius: 40rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		
		.receivedImg {
			width: 280rpx;
			height: 280rpx;
			
			image {
				width: 100%;
				height: 100%;
			}
		}
		
		.receivedTitle {
			font-weight: bold;
			font-size: 36rpx;
			color: #333333;
			margin: 50rpx 0 15rpx 0;
		}
		
		.receivedTip {
			font-size: 28rpx;
			color: #999999;
			margin-bottom: 50rpx;
		}
		
		.receivedBtn {
			width: 336rpx;
			height: 80rpx;
			border-radius: 40rpx;
			border: 2rpx solid #FF3257;
			font-weight: bold;
			font-size: 32rpx;
			color: #FF3257;
			display: flex;
			align-items: center;
			justify-content: center;
		}
	}

</style>